const { Server } = require("socket.io")
const io = new Server(3000, {
  // options
  cors: { origin: ['http://localhost:5173', 'http://127.0.0.1:5173'] }
});
let userlist = []
let newUserList = []
let xt = 0
const content = []
const addUser = (socket) => {
  if (userlist.every(item => item.username != socket.handshake.query.username)) {
    userlist.push({ username: socket.handshake.query.username, id: socket.id })
  } else {
    userlist.forEach(element => {
      element.username === socket.handshake.query.username && (element.id = socket.id)
    });
  }
  socket.emit("login", { userlist, id: socket.id })
}



io.on("connection", (socket) => {
  if (['null', 'undefined', ''].includes(socket.handshake.query.username)) return
  //添加用户
  addUser(socket)
  //检查离线并且删除用户
  if (!xt) {
    xt = setInterval(() => {
      io.emit("xt")
    }, 2000)
    setInterval(() => {
      userlist = [...newUserList]
      newUserList.length = 0
      io.emit("login", { userlist, id: null })
    }, 5000)

  }

  //监听用户是否有接收到在线测试,没有则表示离线
  socket.on("xtEnd", (user) => {
    if (!user) return
    if (newUserList.every(item => item.username != user.username)) {
      newUserList.push({ username: user.username, id: user.id })
    } else {
      newUserList.forEach(element => {
        element.username === user.username && (element.id = user.id)
      });
    }

  })
  //监听用户发送的消息
  socket.on('SendMessage', (message) => {
    let index = 0
    let IsUser = content.some((item, i) => {
      if (item.users.includes(message.users[0]) && item.users.includes(message.users[1])) {
        index = i
        content[index].values.push(...JSON.parse(JSON.stringify(message.values)))
        return true
      }
      return false
    })
    !IsUser && content.push(message)
    io.sockets.sockets.forEach(item => (item.id === message.users[1] || item.id === message.users[0]) && item.emit("SendMessage", IsUser ? content[index] : message))
  })
});
